//
//  ViewController.m
//  1NSThreadDemo创建子线程
//
//  Created by LZXuan on 15-7-1.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "ViewController.h"

#define kScreenSize [UIScreen mainScreen].bounds.size

#define kPrintLog  NSLog(@"func:%s isMain:%d",__func__,[NSThread isMainThread])

@interface ViewController ()

@end

@implementation ViewController

/*
 iOS中 都是异步编程模型
 1.程序起来之后 就有一个UI主线程 主要负责刷新UI 如果有耗时操作一般要交给子线程来做
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *titleArr = @[@"创建线程1",@"创建线程2",@"创建线程3"];
    
    for (NSInteger i = 0; i < titleArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, 100+30*i, kScreenSize.width, 30);
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        button.tag = 101+i;
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
    
    //dsddsds
    /**
     *  <#Description#>
     */
    
    /*
     1.代码写出来之后 要执行调用
     2.执行调用 代码 由主线程或者子线程
     */
    //检测 是否是主线程在执行调用当前函数
    kPrintLog;//主线程执行调用
}

- (void)btnClick:(UIButton *)button {
    //主线程执行调用
    kPrintLog;
    NSLog(@"%@",[NSThread currentThread]);
    switch (button.tag) {
            //创建线程
        case 101:
        {
            //在主线程 执行中创建 子线程
            //1.创建一个后台线程
            [self performSelectorInBackground:@selector(threadClick1:) withObject:@"线程1"];
        }
            break;
        case 102:
        {//2.创建线程
            NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(threadClick2:) object:@"线程2"];
            thread2.name = @"thread2";
            //这种创建方式需要手动启动线程
            [thread2 start];
        }
            break;
        case 103:
        {
            //3/创建子线程 这种方式一旦创建 立即启动
            [NSThread detachNewThreadSelector:@selector(threadClick3:) toTarget:self withObject:@"线程3"];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - 下面的方法 是子线程来执行的方法
- (void)threadClick1:(id)obj {
    //子线程执行调用
    NSLog(@"obj:%@",obj);
    NSLog(@"%@",[NSThread currentThread]);
    kPrintLog;
    //这个函数 调用结束 -->子线程也就结束了
}
- (void)threadClick2:(id)obj {
    //子线程2执行调用
    NSLog(@"obj:%@",obj);
    NSLog(@"%@",[NSThread currentThread]);
    kPrintLog;
    
    for (int i = 0; i < 20; i++) {
        [NSThread sleepForTimeInterval:0.5];
        NSLog(@"i= %d",i);
    }
    //这个函数 调用结束 -->子线程也就结束了
    NSLog(@"线程2即将结束");
}

- (void)threadClick3:(id)obj {
    //子线程3执行调用
    NSLog(@"obj:%@",obj);
    NSLog(@"%@",[NSThread currentThread]);
    kPrintLog;
    for (int i = 0; i < 20; i++) {
        [NSThread sleepForTimeInterval:0.5];
        NSLog(@"i= %d",i);
    }
    //这个函数 调用结束 -->子线程也就结束了
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
